const express = require("express");
const compression = require("compression");
const path = require("path");
const fs = require("fs");

const app = express();

// 配置高级压缩选项
app.use(
    compression({
        level: 9, // 最高压缩级别
        threshold: 0, // 对所有大小的响应都进行压缩
        filter: (req, res) => {
            if (req.headers["x-no-compression"]) {
                return false;
            }
            return compression.filter(req, res);
        },
    })
);

// 自定义静态文件中间件，优先使用 .gz 文件
app.get("*.js", function (req, res, next) {
    const position = path.join(process.cwd(), "src", "public", "dist");
    // 替换路径前缀
    const modifiedUrl = req.url.replace("/webpack-react-start/", "/webpack-react-start-br/");
    const gzipPath = path.join(position, modifiedUrl + ".br");
    if (fs.existsSync(gzipPath)) {
        req.url = modifiedUrl + ".br";
        res.set("Content-Encoding", "br");
    } else {
        req.url = modifiedUrl;
    }
    res.set("Content-Type", "text/javascript");
    next();
});

app.get("*.css", function (req, res, next) {
    const position = path.join(process.cwd(), "src", "public", "dist");
    // 替换路径前缀
    const modifiedUrl = req.url.replace("/webpack-react-start/", "/webpack-react-start-br/");
    const gzipPath = path.join(position, modifiedUrl + ".br");
    if (fs.existsSync(gzipPath)) {
        req.url = modifiedUrl + ".br";
        res.set("Content-Encoding", "br");
    } else {
        req.url = modifiedUrl;
    }
    res.set("Content-Type", "text/css");
    next();
});

// 设置静态文件目录
const distPath = path.join(process.cwd(), "src", "public", "dist", "webpack-react-start-br");
console.log("静态文件目录:", distPath);

// 静态文件服务配置
app.use("/webpack-react-start-br", express.static(distPath));

// 处理所有路由请求，返回 index.html
app.get("/webpack-react-start/*", (req, res) => {
    // res.sendFile(path.join(distPath, "static", "index.html"));
    res.sendFile(path.join(distPath, "index.html"));
});

// 根路径重定向到应用
app.get("/", (req, res) => {
    res.redirect("/webpack-react-start/");
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}/webpack-react-start/`);
});
